package com.ecotope.quartz.module.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.fastjson.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpURLConnectionUtil {

    private static final Logger logger = LoggerFactory.getLogger(HttpURLConnectionUtil.class);

    /**
     * get方式请求
     *
     * @param url 接口服务地址
     * @throws IOException
     */
    public static String getMethod(String url) throws IOException {
        URL restURL = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) restURL.openConnection();
        // POST GET PUT DELETE
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Accept", "application/json");
        BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String line;
        while ((line = br.readLine()) != null) {
            return line;
        }
        br.close();
        return null;
    }

    /**
     * post方式请求
     *
     * @param url   服务地址
     * @param query json格式参数
     * @throws IOException
     */
    public void postMethod(String url, String query) throws IOException {
        URL restURL = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) restURL.openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setDoOutput(true);
        PrintStream ps = new PrintStream(conn.getOutputStream());
        ps.print(query);
        ps.close();
        BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String line;
        while ((line = br.readLine()) != null) {
            logger.info(line);
        }
        br.close();
    }

    /**
     * 判断是否是json字符串
     * @param data
     * @return
     */
    public static boolean isJsonObject(String data) {

        boolean flag = true;
        try {
            JSONObject jsonObject = JSONObject.parseObject(data);
            //yes, it is
        } catch (Exception e) {
            //no, it isnt
            flag = false;
        }
        return flag;
    }
}
